function [kcomplexes] = KComplexes(A)

L = length(A);

Maxes = FindMaxima(A);
Mins  = FindMinima(A);

kcomplexes=0;
sigma = std(A);
i_end = 1;
for i = 21:L
    %M = RunningAverage(A(i-100:i-10));
    found = 0;
    % look for "positive" max
    if (Maxes(i)==1)
        M = mean(A(i-20:i-10));
        if (A(i)>M)
            i_max = i;
            for j = i:L
                % if there's a higher max, go with it
                if (Maxes(i)==1 && A(i)>A(i_max))
                    i = j;
                    break;
                    % capture the right-hand most zero
                elseif (A(j)<M && A(j-1)>M)
                    i_midr = j;
                    % stop when we find a "negative" min
                elseif (Mins(j)==1 && A(j)<M)
                    i_min = j;
                    i = j;
                    found=1;
                    break;
                end
            end
            if (found==1)
                % scan for beginning
                found = 0;
                for j = i_max:-1:max(i_max-100, i_end)
                    if ((1+.10)*(A(i_max)+A(i_min))/2 > A(j)...
                            && (1-.10)*(A(i_max)+A(i_min))/2 < A(j))
                        i_start = j;
                        found = 1;
                        break;
                    end
                end
                % scan for end
                if (found==1)
                    for j = i_min:1:min(i_min+100, L-1)
                        if ((1+.15)*(A(i_max)+A(i_min))/2 > A(j) ...
                               && (1-.15)*(A(i_max)+A(i_min))/2 < A(j))
                            i_end = j;
                            break;
                        end
                    end
                end
                % evaluate once all data is gathered
                if (found==1)
                    i_max = MaximumAt(A(i_start:i_end),i_start);
                    i_min = MinimumAt(A(i_start:i_end),i_start);
                    % if fast then slow
                    if (i_min-i_midr > i_midr-i_max)
                        % at least 50 deciseconds, less than 500
                        if (i_end-i_start > 50 && i_end-i_start < 500)
                            shorter = min(A(i_max)-M, M-A(i_min));
                            longer  = max(A(i_max)-M, M-A(i_min));
                            % if max/min are about same amplitude
                            if (abs(longer/shorter) < 1.5)
                                % standard deviation should be greater
                                if (std(A(i_max:i_min)) > sigma)
                                    %i = i_end;
                                    kcomplexes=kcomplexes+1;
                                end
                            end
                        end
                    end
                end
            end
        end
    end
end
